import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XMLFunction extends Function {

	int size;
	Polynom poly;

	public XMLFunction(String str, int size, double norm) {
		super(norm);
		this.size = size;
		this.poly = xmlToPolynom(str);
	}
	
	@Override
	public Complex getVal(int i) {
		return this.poly.calcPolynom(i, size);
	}

	public static Polynom xmlToPolynom(String filepath){
		 try {
			 Polynom answer = new Polynom();
			 File file = new File(filepath);
			 DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
			 DocumentBuilder bld = fact.newDocumentBuilder();
			 Document fd = bld.parse(file);
			 fd.getDocumentElement().normalize();
			 Element elem = fd.getDocumentElement();
			 String functionID = elem.getAttribute("id");  
			 NodeList nodeList = elem.getElementsByTagName("function");
			 for (int j = 0; j < nodeList.getLength(); j++) {
				 	Node currNode = nodeList.item(j);
				 	Element funcElem = (Element) currNode; 	
				 	if(funcElem.getAttribute("id").equalsIgnoreCase(functionID)){
				 		NodeList monom = funcElem.getElementsByTagName("monom");
				 		double[] realMat = new double[monom.getLength()];
				 		double[] imMat = new double[monom.getLength()];
				 		int[] alphaParts = new int[monom.getLength()];
				 		for(int i=0;i<monom.getLength(); i++){
				 			NodeList realList = funcElem.getElementsByTagName("real");
				 			realMat[i] = new Double(realList.item(i).getTextContent());
				 			NodeList imList = funcElem.getElementsByTagName("image");
				 			imMat[i] = new Double(imList.item(i).getTextContent());
				 			NodeList alphas = funcElem.getElementsByTagName("alpha");
				 			alphaParts[i] = new Integer(alphas.item(i).getTextContent());
				 			answer.addMonom(new Monom(realMat[i],imMat[i],alphaParts[i]));
				 		}
				 		return answer;
				 	}
			 }
	    }catch (Exception err) {
	    	err.printStackTrace();
	    }
	    return null;
	 }
}
